<template>
  <div class="settings-container">
    <a-tabs v-model:activeKey="activeTab">
      <!-- 基本设置 -->
      <a-tab-pane key="basic" tab="基本设置">
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="系统名称" name="systemName">
            <a-input v-model:value="formState.systemName" />
          </a-form-item>

          <a-form-item label="管理员邮箱" name="adminEmail">
            <a-input v-model:value="formState.adminEmail" />
          </a-form-item>

          <a-form-item label="日志级别" name="logLevel">
            <a-select v-model:value="formState.logLevel">
              <a-select-option value="debug">Debug</a-select-option>
              <a-select-option value="info">Info</a-select-option>
              <a-select-option value="warn">Warn</a-select-option>
              <a-select-option value="error">Error</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="日志保留天数" name="logRetentionDays">
            <a-input-number
              v-model:value="formState.logRetentionDays"
              :min="1"
              :max="365"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item label="告警通知" name="enableAlert">
            <a-switch v-model:checked="formState.enableAlert" />
          </a-form-item>

          <a-form-item
            v-if="formState.enableAlert"
            label="告警邮箱"
            name="alertEmails"
          >
            <a-select
              v-model:value="formState.alertEmails"
              mode="tags"
              placeholder="请输入告警邮箱"
              :token-separators="[',']"
            />
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4 }">
            <a-button
              type="primary"
              :loading="loading"
              @click="handleSaveSettings"
            >
              保存设置
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>

      <!-- 系统状态 -->
      <a-tab-pane key="status" tab="系统状态">
        <a-descriptions bordered>
          <a-descriptions-item label="CPU使用率">
            {{ systemStatus.cpuUsage }}%
          </a-descriptions-item>
          <a-descriptions-item label="内存使用率">
            {{ systemStatus.memoryUsage }}%
          </a-descriptions-item>
          <a-descriptions-item label="磁盘使用率">
            {{ systemStatus.diskUsage }}%
          </a-descriptions-item>
          <a-descriptions-item label="系统运行时间">
            {{ systemStatus.uptime }}
          </a-descriptions-item>
          <a-descriptions-item label="Go版本">
            {{ systemStatus.goVersion }}
          </a-descriptions-item>
          <a-descriptions-item label="系统版本">
            {{ systemStatus.version }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-card title="数据库状态">
          <a-descriptions bordered>
            <a-descriptions-item label="MySQL连接数">
              {{ systemStatus.mysqlConnections }}
            </a-descriptions-item>
            <a-descriptions-item label="Redis连接数">
              {{ systemStatus.redisConnections }}
            </a-descriptions-item>
            <a-descriptions-item label="数据库大小">
              {{ systemStatus.databaseSize }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-tab-pane>

      <!-- ��据备份 -->
      <a-tab-pane key="backup" tab="数据备份">
        <a-space direction="vertical" style="width: 100%">
          <a-alert
            message="备份说明"
            description="备份将导出所有数据库数据，包括用户信息、机器码、消息记录等。建议定期备份数据。"
            type="info"
            show-icon
          />

          <a-card title="手动备份">
            <a-space>
              <a-button type="primary" @click="handleBackup">
                <download-outlined /> 立即备份
              </a-button>
              <a-upload
                :customRequest="handleRestore"
                :showUploadList="false"
                accept=".sql,.gz"
              >
                <a-button>
                  <upload-outlined /> 恢复备份
                </a-button>
              </a-upload>
            </a-space>
          </a-card>

          <a-card title="自动备份">
            <a-form layout="vertical">
              <a-form-item label="启用自动备份">
                <a-switch v-model:checked="formState.enableAutoBackup" />
              </a-form-item>

              <template v-if="formState.enableAutoBackup">
                <a-form-item label="备份周期">
                  <a-radio-group v-model:value="formState.backupCycle">
                    <a-radio value="daily">每天</a-radio>
                    <a-radio value="weekly">每周</a-radio>
                    <a-radio value="monthly">每月</a-radio>
                  </a-radio-group>
                </a-form-item>

                <a-form-item label="备份时间">
                  <a-time-picker
                    v-model:value="formState.backupTime"
                    format="HH:mm"
                  />
                </a-form-item>

                <a-form-item label="保留备份数">
                  <a-input-number
                    v-model:value="formState.backupRetention"
                    :min="1"
                    :max="100"
                  />
                </a-form-item>
              </template>
            </a-form>
          </a-card>
        </a-space>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  DownloadOutlined,
  UploadOutlined
} from '@ant-design/icons-vue'
import {
  getSettings,
  updateSettings,
  getSystemStatus,
  backupData,
  restoreData
} from '@/api/settings'

// 标签页相关
const activeTab = ref('basic')

// 表单相关
const formRef = ref()
const loading = ref(false)
const formState = reactive({
  systemName: '',
  adminEmail: '',
  logLevel: 'info',
  logRetentionDays: 30,
  enableAlert: false,
  alertEmails: [],
  enableAutoBackup: false,
  backupCycle: 'daily',
  backupTime: null,
  backupRetention: 7
})

const rules = {
  systemName: [
    { required: true, message: '请输入系统名称' }
  ],
  adminEmail: [
    { required: true, message: '请输入管理员邮箱' },
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  logLevel: [
    { required: true, message: '请选择日志级别' }
  ],
  logRetentionDays: [
    { required: true, message: '请输入日志保留天数' }
  ]
}

// 系统状态
const systemStatus = reactive({
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0,
  uptime: '',
  goVersion: '',
  version: '',
  mysqlConnections: 0,
  redisConnections: 0,
  databaseSize: ''
})

// 获取设置
const fetchSettings = async () => {
  try {
    const { data } = await getSettings()
    Object.assign(formState, data)
  } catch (error) {
    console.error('获取设置失败:', error)
  }
}

// 获取系统状态
const fetchSystemStatus = async () => {
  try {
    const { data } = await getSystemStatus()
    Object.assign(systemStatus, data)
  } catch (error) {
    console.error('获取系统状态失败:', error)
  }
}

// 保存设置
const handleSaveSettings = () => {
  formRef.value.validate().then(async () => {
    loading.value = true
    try {
      await updateSettings(formState)
      message.success('保存成功')
    } catch (error) {
      console.error('保存设置失败:', error)
    } finally {
      loading.value = false
    }
  })
}

// 备份数据
const handleBackup = async () => {
  try {
    const response = await backupData()
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `backup_${Date.now()}.sql.gz`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    message.success('备份成功')
  } catch (error) {
    console.error('备份失败:', error)
    message.error('备份失败')
  }
}

// 恢复数据
const handleRestore = async ({ file }) => {
  try {
    await restoreData(file)
    message.success('恢复成功')
  } catch (error) {
    console.error('恢复失败:', error)
    message.error('恢复失败')
  }
}

onMounted(() => {
  fetchSettings()
  fetchSystemStatus()
  // 定时刷新系统状态
  setInterval(fetchSystemStatus, 30000)
})
</script>

<style scoped>
.settings-container {
  padding: 24px;
  background: #fff;
}
</style> 